<template>
  <div class="user-container">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <el-input
          v-model="data.realName"
          placeholder="请输入用户姓名查询"
          class="search-input"
          :prefix-icon="Search"
      />
      <el-button type="danger" plain @click="load()">查询</el-button>
      <el-button type="danger" plain @click="reset">重置</el-button>
    </div>

    <!-- 数据表格卡片 -->
    <div class="data-card">
      <div class="button-group">
        <el-button type="danger" @click="handleAdd">
          <el-icon>
            <Plus/>
          </el-icon>
          新增用户
        </el-button>
        <el-button type="danger" plain @click="delBatch">
          <el-icon>
            <Delete/>
          </el-icon>
          批量删除
        </el-button>
      </div>

      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="realName" label="真实姓名"/>
        <el-table-column prop="phone" label="手机号" width="150"/>
        <el-table-column prop="email" label="邮箱" width="180"/>
        <el-table-column prop="userType" label="用户类型">
          <template #default="scope">
            <el-tag :type="getUserTypeTag(scope.row.userType)">
              {{ getUserTypeLabel(scope.row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170"/>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <el-button size="default" type="danger" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <!-- 用户表单对话框 -->
    <!-- 用户表单对话框 -->
    <el-dialog
        :title="data.form.id ? '编辑用户' : '新增用户'"
        v-model="data.formVisible"
        width="900px"
        destroy-on-close
    >
      <el-form
          :model="data.form"
          :rules="rules"
          ref="userRef"
          label-width="100px"
      >
        <el-row :gutter="20">
          <!-- 左侧列 - 基本信息 -->
          <el-col :span="12">
            <div class="form-section">
              <h3 class="section-title">基本信息</h3>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="data.form.username" />
              </el-form-item>
              <el-form-item label="真实姓名" prop="realName">
                <el-input v-model="data.form.realName" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="data.form.phone" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="data.form.email" />
              </el-form-item>
              <el-form-item label="用户类型" prop="userType">
                <el-select v-model="data.form.userType" placeholder="请选择用户类型" @change="handleUserTypeChange">
                  <el-option label="校团委书记" :value="1" />
                  <el-option label="院团委书记" :value="2" />
                  <el-option label="班团委书记" :value="3" />
                  <el-option label="教师" :value="4" />
                  <el-option label="学生" :value="5" />
                  <el-option label="系统管理员" :value="6" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="data.form.status">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </el-col>

          <!-- 右侧列 - 学生信息 -->
          <el-col :span="12">
            <div class="form-section" v-if="data.form.userType === 5">
              <h3 class="section-title">学生信息</h3>
              <el-form-item label="学号" prop="studentInfo.studentNumber">
                <el-input v-model="data.form.studentInfo.studentNumber" />
              </el-form-item>
              <el-form-item label="院系" prop="studentInfo.department">
                <el-input v-model="data.form.studentInfo.department" />
              </el-form-item>
              <el-form-item label="专业" prop="studentInfo.major">
                <el-input v-model="data.form.studentInfo.major" />
              </el-form-item>
              <el-form-item label="班级" prop="studentInfo.className">
                <el-input v-model="data.form.studentInfo.className" />
              </el-form-item>
              <el-form-item label="年级" prop="studentInfo.grade">
                <el-input v-model="data.form.studentInfo.grade" />
              </el-form-item>
              <el-form-item label="性别" prop="studentInfo.sex">
                <el-radio-group v-model="data.form.studentInfo.sex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="政治面貌" prop="studentInfo.politicalStatus">
                <el-select v-model="data.form.studentInfo.politicalStatus">
                  <el-option label="共青团员团员" :value="2" />
                  <el-option label="入党积极分子" :value="3" />
                  <el-option label="发展对象" :value="4" />
                  <el-option label="预备党员" :value="5" />
                  <el-option label="正式党员" :value="6" />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-section" v-if="data.form.userType === 1 || data.form.userType === 2">
              <h3 class="section-title">{{ data.form.userType === 1 ? '校团支书' : '院团支书' }}信息</h3>
              <el-form-item label="成员编号" prop="memberInfo.memberNo">
                <el-input v-model="data.form.memberInfo.memberNo" />
              </el-form-item>
              <el-form-item label="所属支部" prop="memberInfo.branchId">
                <el-select v-model="data.form.memberInfo.branchId" placeholder="请选择所属支部">
                  <el-option
                      v-for="item in data.branchOptions"
                      :key="item.id"
                      :label="item.branchName"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="入团时间" prop="memberInfo.joinTime">
                <el-date-picker
                    v-model="data.form.memberInfo.joinTime"
                    type="datetime"
                    placeholder="选择时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="转正时间" prop="memberInfo.formalTime">
                <el-date-picker
                    v-model="data.form.memberInfo.formalTime"
                    type="datetime"
                    placeholder="选择时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="介绍人" prop="memberInfo.recommender">
                <el-input v-model="data.form.memberInfo.recommender" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="danger" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const emptyStudentInfo = {
  studentNumber: '',
  department: '',
  major: '',
  className: '',
  grade: '',
  sex: '男',
  politicalStatus: 1
}
const defaultForm = {
  id: null,
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  avatar: '',
  userType: null,
  status: 1,
  studentInfo: {
    studentNumber: '',
    department: '',
    major: '',
    className: '',
    grade: '',
    sex: '男',
    politicalStatus: 1
  },
  memberInfo: {
    memberNo: '',
    branchId: null,
    joinTime: '',
    formalTime: '',
    recommender: '',
    memberStatus: 1,
    orgType: null
  }
}

// 定义响应式数据
const data = reactive({
  realName: '',
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {
    studentInfo: emptyStudentInfo
  },
  multipleSelection: [],
  branchOptions: [],
})

const rules = {
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  realName: [{required: true, message: '请输入真实姓名', trigger: 'blur'}],
  phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
  email: [{required: true, message: '请输入手机号', trigger: 'blur', type: 'email'}],
  userType: [{required: true, message: '请选择用户类型', trigger: 'change'}],
  'studentInfo.studentNumber': [
    {required: true, message: '请输入学号', trigger: 'blur'}
  ],
  'studentInfo.department': [
    {required: true, message: '请输入院系', trigger: 'blur'}
  ],
  'studentInfo.major': [
    {required: true, message: '请输入专业', trigger: 'blur'}
  ],
  'studentInfo.className': [
    {required: true, message: '请输入班级', trigger: 'blur'}
  ],
  'studentInfo.grade': [
    {required: true, message: '请输入年级', trigger: 'blur'}
  ],
  'studentInfo.politicalStatus': [
    {required: true, message: '请选择政治面貌', trigger: 'change'}
  ],
  'memberInfo.branchId': [{ required: true, message: '请选择所属支部', trigger: 'change' }],
  'memberInfo.memberNo': [{ required: true, message: '请输入成员编号', trigger: 'blur' }],
  'memberInfo.joinTime': [{ required: true, message: '请选择入党/团时间', trigger: 'change' }],
  'memberInfo.memberStatus': [{ required: true, message: '请选择成员状态', trigger: 'change' }],
  'memberInfo.recommender': [{ required: true, message: '请输入介绍人', trigger: 'blur' }]
}

// 用户类型变更处理
const handleUserTypeChange = (value) => {
  if (value === 5) {
    // 如果选择学生类型，初始化学生信息对象
    data.form.studentInfo = { ...emptyStudentInfo }
    data.form.memberInfo = null
  } else if (value === 1 || value === 2) {
    // 如果选择党/团委书记，初始化成员信息对象
    data.form.studentInfo = null
    data.form.memberInfo = {
      memberNo: '',
      branchId: null,
      joinTime: '',
      formalTime: '',
      recommender: '',
      memberStatus: 1,
      orgType: value // 1为党组织，2为团组织
    }
    // 加载对应类型的支部选项
    loadBranchOptions(value)
  } else {
    // 其他类型清空所有附加信息
    data.form.studentInfo = null
    data.form.memberInfo = null
  }
}


// 加载支部选项
const loadBranchOptions = async (orgType) => {
  try {
    const res = await request.get('/organizationBranch/selectAll', {
      params: { orgType }
    })
    if (res.code === '200') {
      data.branchOptions = res.data
    }
  } catch (error) {
    ElMessage.error('获取支部列表失败')
  }
}


const getUserTypeLabel = (type) => {
  const types = {
    1: '校团委书记',
    2: '院级委书记',
    3: '班级团委书记',
    4: '教师',
    5: '学生',
    6: '系统管理员'
  }
  return types[type] || '未知'
}

const getUserTypeTag = (type) => {
  const tags = {
    1: 'warning', // 校团委书记
    2: 'warning', // 院级团委书记
    3: 'warning', // 班级团委书记
    4: 'success', // 教师
    5: 'success', // 学生
    6: ''
  }
  return tags[type] || ''
}
// 分页查询
const load = () => {
  request.get('/sysUser/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      realName: data.realName,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list
      data.total = res.data?.total
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()
// 新增数据
const handleAdd = () => {
  data.form =   { ...defaultForm }
  data.formVisible = true
}

// 编辑数据
const handleEdit = async (row) => {
  data.form = JSON.parse(JSON.stringify(row))

  if (row.userType === 5) {
    // 获取学生信息
    try {
      const res = await request.get('/studentInfo/getByUserId/' + row.id)
      if (res.code === '200') {
        data.form.studentInfo = res.data || {}
      }
    } catch (error) {
      ElMessage.error('获取学生信息失败')
    }
  } else if (row.userType === 1 || row.userType === 2) {
    // 获取党/团委书记信息
    try {
      const res = await request.get('/organizationMember/getByUserId/' + row.id)
      if (res.code === '200') {
        // 处理时间格式
        const memberInfo = res.data || {}
        if (memberInfo.joinTime) {
          memberInfo.joinTime = formatDateTime(memberInfo.joinTime)
        }
        if (memberInfo.formalTime) {
          memberInfo.formalTime = formatDateTime(memberInfo.formalTime)
        }
        data.form.memberInfo = memberInfo
        await loadBranchOptions(row.userType)
      }
    } catch (error) {
      ElMessage.error('获取组织成员信息失败')
    }
  }
  data.formVisible = true
}

// 添加时间格式化函数
const formatDateTime = (time) => {
  if (!time) return ''
  // 如果时间已经是yyyy-MM-dd HH:mm:ss格式，直接返回
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(time)) {
    return time
  }
  // 处理其他可能的时间格式
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


// 保存数据
const save = () => {
  const url = data.form.id ? '/sysUser/update' : '/sysUser/add'
  const method = data.form.id ? 'PUT' : 'POST'

  // 构建要保存的数据
  const saveData = {
    ...data.form,
    studentInfo: data.form.userType === 5 ? data.form.studentInfo : null,
    memberInfo: (data.form.userType === 1 || data.form.userType === 2) ? {
      ...data.form.memberInfo,
      // 确保时间格式正确
      joinTime: data.form.memberInfo.joinTime ? formatDateTime(data.form.memberInfo.joinTime) : null,
      formalTime: data.form.memberInfo.formalTime ? formatDateTime(data.form.memberInfo.formalTime) : null,
      orgType: data.form.userType
    } : null,
  }

  request({
    url,
    method,
    data: saveData
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('保存成功')
      data.formVisible = false
      data.form = { ...defaultForm }
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('您确定删除吗？', '确认删除', {type: 'warning'}).then(() => {
    request.delete('/sysUser/delete/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
  })
}


// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('您确定批量删除这些数据吗？', '确认删除', {type: 'warning'}).then(() => {
    request.delete('/sysUser/delete/batch', {data: data.ids}).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
  })
}

// 处理选中的行
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 重置筛选条件
const reset = () => {
  data.realName = null
  load()
}
// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum
  load(pageNum)
}
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize
  load()
}
const userRef = ref()
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必须的参数！')
      return false
    }
  })
}
</script>

<style scoped>
/* 容器和卡片基础样式 */
.user-container {
  padding: 20px;
}

.search-card,
.data-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-card {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

/* 搜索和按钮组件 */
.search-input {
  width: 300px;
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Element Plus 主题定制 */
:deep(.el-table) {
  --el-table-header-bg-color: #fff5f5;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #c8161d;
  --el-button-border-color: #c8161d;
  --el-button-hover-bg-color: #e54b4b;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #c8161d;
  --el-button-active-border-color: #c8161d;
  --el-button-text-color: #fff;
}

:deep(.el-button--danger.is-plain) {
  --el-button-bg-color: #fff;
  --el-button-border-color: #c8161d;
  --el-button-text-color: #c8161d;
  --el-button-hover-text-color: #c8161d;
  --el-button-hover-bg-color: #fff5f5;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #fff5f5;
  --el-button-active-text-color: #c8161d;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #c8161d;
}

/* 按钮动画效果 */
:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button:active) {
  transform: scale(0.98);
}

.form-section {
  padding: 0 10px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-select) {
  width: 100%;
}

/* 调整dialog的样式 */
:deep(.el-dialog) {
  --el-dialog-padding-primary: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>

